﻿using System;
using System.Data;
using System.Threading;
using System.Windows.Forms;
using ChinaDynastyTours.Assets;
using ChinaDynastyTours.Assets.DataSet;
using ChinaDynastyTours.Controls;
using ChinaDynastyTours.Helpers;
using ChinaDynastyTours.Models;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;

namespace ChinaDynastyTours.Views
{
    public partial class LocalPlanScheduleForm : DevExpress.XtraEditors.XtraForm
    {
        public DataView _TourGroupDataTable { get; set; }
        public int _Position { get; set; }
        private DataTable _ScheduleData = null;

        private int _currentPageNumber = 1; //当前页号
        private int _totalPageNumbers;  //总页号
        private string _firstlocalPlanScheduleID = "";//第一行本地行程ID
        //private string _Remark = "";

        public LocalPlanScheduleForm(DataView tourGroupDataTable)//, int rowID)
        {
            InitializeComponent();
        
            _TourGroupDataTable = tourGroupDataTable;
            //_Position = rowID;
            //_Remark = _TourGroupDataTable[0]["LocalRemark"].ToString();
        }
    
 
        #region 窗口初始化

        private void LocalPlanScheduleForm_Load(object sender, EventArgs e)
        {
            //初始化团基本信息显示
            InitGui();
            this.BindingContext[_TourGroupDataTable].Position = _Position;

            //初始化计划内容
            //LoadScheduleGridViewData();
            UpdateButtonStatus();
            LoadSelectPage(1);
            _firstlocalPlanScheduleID = scheduleGridView.GetRowCellValue(0, "LocalPlanScheduleID").ToString();

            #region 团状态按钮处理

            DataRowView drv = (BindingContext[_TourGroupDataTable].Current as DataRowView);
            switch (TeamGroupCtrl.GetTourGroupState(lblTourGroupID.Text))
            {
                case TeamStateEnum.审核:
                case TeamStateEnum.终结:
                    btnAdd.Enabled = false;
                    btnDelete.Enabled = false;
                    btnFun.Enabled = false;
                    btnRestaurant.Enabled = false;
                    btnVehicle.Enabled = false;
                    mbLocalRemark.Enabled = false;
                    scheduleGridView.OptionsBehavior.Editable = false;
                    break;
                default:
                    break;
            }
            #endregion
        }

        //计划行程数据加载
        private void LoadSelectPage(int pageNumber)
        {
            //提供‘城市’选择         
            //StartAndEndCityEdit.DataSource = BaseInfoCtrl.GetCityData();

            _ScheduleData = LocalTeamGroupCtrl.GetLocalPlanSchedule(lblTourGroupID.Text,pageNumber);
            scheduleGridControl.DataSource = _ScheduleData;

            //赋值CiceroniID并引发tbCiceroni_EditValueChanged事件
            tbCiceroni.EditValue = LocalTeamGroupCtrl.GetLocalPlanScheduleCiceroniIDByPageNumber(lblTourGroupID.Text, pageNumber);
            

            //为行程计划网格‘视图’注册数据更新事件
            _ScheduleData.RowDeleted += new DataRowChangeEventHandler(Table_RowDeleted);
            _ScheduleData.RowChanged += new DataRowChangeEventHandler(Table_RowChanged);
        
            UpdateButtonStatus();
        }

        private void tbCiceroni_EditValueChanged(object sender, EventArgs e)
        {
            if (tbCiceroni.EditValue == DBNull.Value)
            {
                tbPhone.EditValue = "";
                return;
            }
            string ciceroniId = tbCiceroni.EditValue.ToString();
            tbPhone.EditValue = BaseInfoCtrl.GetCiceroniPhoneById(ciceroniId);
            LocalTeamGroupCtrl.UpdateLocalTourGroupScheduleCiceroniData(lblTourGroupID.Text,_currentPageNumber,ciceroniId,tbCiceroni.Text,tbPhone.Text);
        }
        //初始化界面内容
        private void InitGui()
        {
            //tbCiceroni.Properties.DataSource = BaseInfoCtrl.GetCiceroniNameData("");
            //tbCiceroni.Properties.DisplayMember = "CiceroniName";
            //tbCiceroni.Properties.ValueMember = "CiceroniID";      
 
            //团状态信息
            lblTourGroupID.DataBindings.Add("Text", _TourGroupDataTable, "TourgroupID");
            lblTourGroupName.DataBindings.Add("Text", _TourGroupDataTable, "TourgroupName");


            tbCountry.DataBindings.Add("EditValue", _TourGroupDataTable, "Country");
            lblCountryCode.DataBindings.Add("Text", _TourGroupDataTable, "CountryCode");
            tbStartDate.DataBindings.Add("EditValue", _TourGroupDataTable, "StartDate");
            tbEndDate.DataBindings.Add("EditValue", _TourGroupDataTable, "EndDate");
            tbNightNum.DataBindings.Add("EditValue", _TourGroupDataTable, "StayOver");
            tbAdultNum.DataBindings.Add("EditValue", _TourGroupDataTable, "AdultNum");
            tbChildNum.DataBindings.Add("EditValue", _TourGroupDataTable, "ChildNum");
            tbTourgroupName.DataBindings.Add("EditValue", _TourGroupDataTable, "TourgroupName");
            cbGuesttype.DataBindings.Add("EditValue", _TourGroupDataTable, "Guesttype");
            cbServicetype.DataBindings.Add("EditValue", _TourGroupDataTable, "Servicetype");
            cbTourgrouptype.DataBindings.Add("EditValue", _TourGroupDataTable, "Tourgrouptype");
            tbAccompanyNum.DataBindings.Add("EditValue", _TourGroupDataTable, "AccompanyNum");
            tbCustomerCode.DataBindings.Add("EditValue", _TourGroupDataTable, "CustomerCode");
            lblCustomerName.DataBindings.Add("Text", _TourGroupDataTable, "CustomerName");
            cbOwnerA.DataBindings.Add("EditValue", _TourGroupDataTable, "OwnerA");
            cbOwnerB.DataBindings.Add("EditValue", _TourGroupDataTable, "OwnerB");
            ckHasGuide.DataBindings.Add("Checked", _TourGroupDataTable, "HasGuide");
            tbBuildGroupDate.DataBindings.Add("EditValue", _TourGroupDataTable, "BuildGroupDate");
            mbLocalRemark.DataBindings.Add("EditValue", _TourGroupDataTable, "LocalRemark");//此备注通过绑定显示数据，通过‘关闭’按钮保存更新数据
            
            string rowState = _TourGroupDataTable[0]["LocalTourgroupRowState"].ToString();//.Rows[_Position]["LocalTourgroupRowState"].ToString();
            tbLocalTourgroupRowState.Checked = (rowState == "2");

            tbCiceroni.Properties.DataSource = GuideArrangeCtrl.GetGuideInfoForPrint(lblTourGroupID.Text);//BaseInfoCtrl.GetCiceroniNameData("");
            tbCiceroni.Properties.DisplayMember = "CiceroniName";
            tbCiceroni.Properties.ValueMember = "CiceroniID";      
        }
        #endregion

        #region 计划行程数据变化后的后台处理
        void Table_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            if (e.Action == DataRowAction.Change || e.Action == DataRowAction.ChangeCurrentAndOriginal || e.Action == DataRowAction.ChangeOriginal)
            {

                LocalPlanScheduleEntity schedule = new LocalPlanScheduleEntity();
                schedule.TourgroupID = this.lblTourGroupID.Text;
                schedule.Date = DateTime.Parse(e.Row["Date"].ToString()).ToString("yyyy-MM-dd");
                schedule.Time = DateTime.Parse(e.Row["Time"].ToString()).ToString("HH:mm:ss");
                schedule.StayOver = int.Parse(e.Row["StayOver"].ToString());
                schedule.Journeytype = e.Row["Journeytype"].ToString();
                schedule.StartCity = e.Row["StartCity"].ToString();
                schedule.DestinationCity = e.Row["DestinationCity"].ToString();
                schedule.TrafficType = e.Row["TrafficType"].ToString();
                schedule.Traffic = e.Row["Traffic"].ToString();
                schedule.TravelAgencyID = int.Parse(e.Row["TravelAgencyID"].ToString());
                schedule.TravelAgencyName = e.Row["TravelAgencyName"].ToString();
                schedule.Reception = e.Row["Reception"].ToString();
                schedule.TicketType = e.Row["TicketType"].ToString();
                schedule.Context = e.Row["Context"].ToString();
                schedule.Dining = e.Row["Dining"].ToString();
                schedule.Hotel = e.Row["Hotel"].ToString();
                schedule.HotelID = int.Parse(e.Row["HotelID"].ToString());
                //schedule.CiceroniID = e.Row["CiceroniID"] == DBNull.Value ? 0 : int.Parse(e.Row["CiceroniID"].ToString());
                //schedule.CiceroniName = e.Row["CiceroniName"].ToString();
                //schedule.Phone = e.Row["Phone"].ToString();

                schedule.LocalPlanScheduleID = int.Parse(e.Row["LocalPlanScheduleID"].ToString());

                LocalTeamGroupCtrl.UpdateLocalTourGroupSchedule(schedule);
            }
        }

        private void Table_RowDeleted(object sender, DataRowChangeEventArgs e)
        {
            if (e.Action == DataRowAction.Delete)
            {
                string localPlanScheduleID = e.Row["LocalPlanScheduleID", DataRowVersion.Original].ToString();
                if (localPlanScheduleID == "")
                    return;

                int scheduleID = int.Parse(localPlanScheduleID);
                
                //将已有预订挪至第一天的行程中
                EntertainmenRestaurantOrderCtrl.UpdateEntertainmenRestauranLocalScheduleID(localPlanScheduleID, _firstlocalPlanScheduleID);
                VehicleOrderCtrl.UpdateVehicleLocalScheduleID(localPlanScheduleID, _firstlocalPlanScheduleID);

            
                //删除行程计划数据
                LocalTeamGroupCtrl.DeleteLocalTourGroupSchedule(scheduleID);
            }
            //刷新
            LoadProvidersListData();
        }

        #endregion

        #region 右键菜单处理 娱乐(演出门票、景点门票)、餐厅、汽车

        private void mnuFun_Click(object sender, EventArgs e)
        {
            EntertainmenOrderForm enterRestOrderForm = new EntertainmenOrderForm(0)
            { 
                _TourGroupID=lblTourGroupID.Text,
                _LocalPlanScheduleDate = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, "Date").ToString(),
                _LocalPlanScheduleID=scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle,"LocalPlanScheduleID").ToString(),
                _TourGroupScheduleID = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, "TourGroupScheduleID").ToString(),
                _AdultNum = tbAdultNum.EditValue == DBNull.Value ? 0 : int.Parse(tbAdultNum.EditValue.ToString()),
                _ChildNum = tbChildNum.EditValue == DBNull.Value ? 0 : int.Parse(tbChildNum.EditValue.ToString()),
                _CiceroniName = tbCiceroni.Text,
                _CiceroniPhone = tbPhone.Text
                //_AccompanyNum = tbAccompanyNum.EditValue == DBNull.Value ? 0 : int.Parse(tbAccompanyNum.EditValue.ToString())  
                //团的全陪数，不是娱乐餐厅的陪同数。娱乐餐厅的陪同数一般是司机和地陪
            };
            enterRestOrderForm.ShowDialog(this);
            //刷新
            LoadProvidersListData();
        }

        private void mnuRestaurant_Click(object sender, EventArgs e)
        {
            RestaurantOrderForm enterRestOrderForm = new RestaurantOrderForm()
            { 
                _TourGroupID=lblTourGroupID.Text,
                _LocalPlanScheduleDate = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, "Date").ToString(),
                _LocalPlanScheduleID = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, "LocalPlanScheduleID").ToString(),
                _TourGroupScheduleID = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, "TourGroupScheduleID").ToString(),
                _AdultNum=tbAdultNum.EditValue==DBNull.Value?0:int.Parse(tbAdultNum.EditValue.ToString()),
                _ChildNum = tbChildNum.EditValue == DBNull.Value ? 0 : int.Parse(tbChildNum.EditValue.ToString()),
                _CiceroniName=tbCiceroni.Text,
                _CiceroniPhone=tbPhone.Text
                //_AccompanyNum = tbAccompanyNum.EditValue == DBNull.Value ? 0 : int.Parse(tbAccompanyNum.EditValue.ToString())
            };
            enterRestOrderForm.ShowDialog(this);
            
            //string diningContext  = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, "Dining").ToString();
            scheduleGridView.SetRowCellValue(scheduleGridView.FocusedRowHandle, "Dining", enterRestOrderForm._returnRestaurant);
            //刷新
            LoadProvidersListData();
        }

        private void mnuVehicle_Click(object sender, EventArgs e)
        {
           string arrivalFlight,arrivalTime,leaveFlight,leaveTime;
           switch (_ScheduleData.Rows.Count)
           {
               case 1://只有一条数据
                   arrivalFlight=_ScheduleData.Rows[0]["Traffic"].ToString();
                   arrivalTime = _ScheduleData.Rows[0]["Date"].ToString() + ' ' + DateTime.Parse(_ScheduleData.Rows[0]["Time"].ToString()).ToString("HH:mm");
                   leaveFlight=_ScheduleData.Rows[0]["Traffic"].ToString();
                   leaveTime = _ScheduleData.Rows[0]["Date"].ToString() + ' ' + DateTime.Parse(_ScheduleData.Rows[0]["Time"].ToString()).ToString("HH:mm");
                   break;
               default://大于等于2条以上，取第1和最后一条数据
                   arrivalFlight=_ScheduleData.Rows[0]["Traffic"].ToString();
                   arrivalTime = _ScheduleData.Rows[0]["Date"].ToString() + ' ' + DateTime.Parse(_ScheduleData.Rows[0]["Time"].ToString()).ToString("HH:mm");
                   leaveFlight=_ScheduleData.Rows[_ScheduleData.Rows.Count-1]["Traffic"].ToString();
                   leaveTime = _ScheduleData.Rows[_ScheduleData.Rows.Count - 1]["Date"].ToString() + ' ' + DateTime.Parse(_ScheduleData.Rows[_ScheduleData.Rows.Count - 1]["Time"].ToString()).ToString("HH:mm");
                   break;
           }

           VehicleOrderForm vhicleOrderForm = new VehicleOrderForm()
            {
                _TourGroupID = lblTourGroupID.Text,
                _LocalPlanScheduleDate = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, "Date").ToString(),
                _LocalPlanScheduleID = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, "LocalPlanScheduleID").ToString(),
                _TourGroupScheduleID = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, "TourGroupScheduleID").ToString(),
                _AdultNum = tbAdultNum.EditValue == DBNull.Value ? 0 : int.Parse(tbAdultNum.EditValue.ToString()),
                _ChildNum = tbChildNum.EditValue == DBNull.Value ? 0 : int.Parse(tbChildNum.EditValue.ToString()),
                _HotelName = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, "Hotel").ToString(),
                _ArrivalFlight = arrivalFlight,
                _ArrivalTime = arrivalTime,
                _LeaveFlight = leaveFlight,
                _LeaveTime = leaveTime,
                _CiceroniName = tbCiceroni.Text,
                _CiceroniPhone = tbPhone.Text
            };
            vhicleOrderForm.ShowDialog(this);
            //刷新
            LoadProvidersListData();
        }

        #endregion

        #region 窗口底部系列按钮事件处理

        #region 分页处理

        private void UpdateButtonStatus()
        {
            _totalPageNumbers = LocalTeamGroupCtrl.GetLocalPlanSchedulePageNumbers(lblTourGroupID.Text);

            btnPrevPage.Enabled = !(_currentPageNumber == 1);
            btnNextPage.Enabled = !(_currentPageNumber == _totalPageNumbers);
            llbCurrentPage.Text = string.Format("第{0}页/共{1}页", _currentPageNumber, _totalPageNumbers);
        }
        private void btnCopyCurrentPage_Click(object sender, EventArgs e)
        {
            string tourgroupName = TeamGroupCtrl.GetTeamGroupNameById(lblTourGroupID.Text);

            //获取当前行程计划列表中的信息
            foreach (DataRow dr in _ScheduleData.Rows)
            {
                LocalPlanScheduleEntity entity = new LocalPlanScheduleEntity()
                {
                    Date = dr["Date"].ToString(),
                    Time = dr["Time"].ToString(),
                    Context = dr["Context"].ToString(),
                    StartCity = dr["StartCity"].ToString(),
                    DestinationCity = dr["DestinationCity"].ToString(),
                    Dining = "",
                    Journeytype = dr["Journeytype"].ToString(),
                    Reception = dr["Reception"].ToString(),
                    StayOver = int.Parse(dr["StayOver"].ToString()),
                    TicketType = dr["TicketType"].ToString(),
                    TourGroupScheduleID = int.Parse(dr["TourGroupScheduleID"].ToString()),
                    Traffic = dr["Traffic"].ToString(),
                    TrafficType = dr["TrafficType"].ToString(),
                    TravelAgencyID = int.Parse(dr["TravelAgencyID"].ToString()),
                    TravelAgencyName = dr["TravelAgencyName"].ToString(),
                    Hotel = dr["Hotel"].ToString(),
                    HotelID = int.Parse(dr["HotelID"].ToString()),
                    Seat = dr["Seat"].ToString(),
                    TourgroupID = dr["TourgroupID"].ToString(),
                    PageNumber = _totalPageNumbers + 1//总页号加1
                };
                LocalTeamGroupCtrl.CreateLocalTourGroupSchedule(entity);
            }
            //加载新建页内容
            _currentPageNumber = _totalPageNumbers + 1;
            LoadSelectPage(_currentPageNumber);
            LoadProvidersListData();
        }
        private void btnPrevPage_Click(object sender, EventArgs e)
        {
            LoadSelectPage(--_currentPageNumber);
            LoadProvidersListData();
        }

        private void btnNextPage_Click(object sender, EventArgs e)
        {
            LoadSelectPage(++_currentPageNumber);
            LoadProvidersListData();
            
        }        
        #endregion

        private void btnAdd_Click(object sender, EventArgs e)
        {
            int tourGroupScheduleId = int.Parse(scheduleGridView.GetRowCellValue(scheduleGridView.DataRowCount - 1, "TourGroupScheduleID").ToString());//取最后一条数据的大行程计划
            LocalPlanScheduleEntity entity = new LocalPlanScheduleEntity();
            entity.TourgroupID = lblTourGroupID.Text;
            entity.TourGroupScheduleID = tourGroupScheduleId;//本条本地行程计划与大行程计划号关联，用于费用管理时各预定项能与大行程计划相关联，此处的关联有些牵强，但没办法，shit！
            entity.Time = "00:00:00";
            entity.StayOver = 1;
            entity.Journeytype = "入境";
            entity.PageNumber = _currentPageNumber;//当前页号

            if (scheduleGridView.RowCount > 0)
            {
                int StayOver = int.Parse(scheduleGridView.GetRowCellDisplayText(scheduleGridView.RowCount - 1, "StayOver"));
                entity.Date = DateTime.Parse(scheduleGridView.GetRowCellDisplayText(scheduleGridView.RowCount - 1, "Date")).AddDays(StayOver).ToString("yyyy-MM-dd");//上一条日期+过夜数
            }
            else
                entity.Date = tbStartDate.DateTime.ToString("yyyy-MM-dd");

            LocalTeamGroupCtrl.CreateLocalTourGroupSchedule(entity);

            //刷新网格
            LoadSelectPage(_currentPageNumber);
            //LoadScheduleGridViewData();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定删除选中计划信息吗？", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                //最后一行不允许删除
                if (_totalPageNumbers == 1 && scheduleGridView.DataRowCount <= 1) //只剩余一页，且页中的只剩一行
                //if (scheduleGridView.DataRowCount <= 1) 
                {
                    MessageBox.Show("最后一条不允许删除！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else if (scheduleGridView.FocusedRowHandle >= 0)
                {
                    //_ScheduleData
                    scheduleGridView.GetDataRow(scheduleGridView.GetSelectedRows()[0]).Delete();//取得第一行选中数据
                    scheduleGridView.Focus();//激活GridView控件，引发Table_RowDeleted完成删除工作
                    _ScheduleData.AcceptChanges();//同步Grid视图中的删除

                    //判断是否页中的内容已空，则重新排列页号
                    if (scheduleGridView.DataRowCount == 0)
                    {
                        LocalTeamGroupCtrl.UpdateLocalTourGroupSchedulePageNumber(lblTourGroupID.Text, _currentPageNumber);
                        //刷新前一页内容
                        if (_currentPageNumber > 0)
                            LoadSelectPage(_currentPageNumber - 1);
                    }

                }
            }
        }

        private void btnPreviewAndPrint_Click(object sender, EventArgs e)
        {
            SimpleButton btn = sender as SimpleButton;

            LocalPlanScheduleDataSet scheduleDs = new LocalPlanScheduleDataSet();

            //获取对应团信息，填充到打印数据集中
            DataTable dtTourgroup = TeamGroupCtrl.GetTeamGroupDataForSchedulePrint(lblTourGroupID.Text);

            //scheduleDs.Tables["Team"].ImportRow((BindingContext[_TourGroupDataTable].Current as DataRowView).Row);
            foreach (DataRow dr in dtTourgroup.Rows)
            {
                scheduleDs.Tables["Team"].ImportRow(dr);
            }


            //获取对应行程信息，填充到打印数据集中
            DataTable dtSchedule = LocalTeamGroupCtrl.GetLocalPlanScheduleForPrint(lblTourGroupID.Text,_currentPageNumber);
            foreach (DataRow dr in dtSchedule.Rows)
            {
                dr["Date"] = DateTime.Parse(dr["Date"].ToString()).ToString("yy-MM-dd ddd");
                dr["Time"] = DateTime.Parse(dr["Time"].ToString()).ToString("HH:mm");
                scheduleDs.Tables["LocalPlanSchedule"].ImportRow(dr);
            }

            //获取对应导游信息，填充到打印数据集中
            DataTable dtGuide = GuideArrangeCtrl.GetGuideInfoForPrint(lblTourGroupID.Text);
            GuideDataSet guideDs = new GuideDataSet();
            foreach (DataRow dr in dtGuide.Rows)
            {
                dr["StartDate"] = DateTime.Parse(dr["StartDate"].ToString()).ToString("yyyy-MM-dd HH:mm");
                guideDs.Tables["Ciceroni"].ImportRow(dr);
            }

            
            //获取对应娱乐餐厅信息，填充到打印数据集中
            DataTable dtProvider = TeamGroupCtrl.GetEntertainmenRestaurantInfoForPrint(lblTourGroupID.Text, _currentPageNumber);
            ProviderDataSet providerDs = new ProviderDataSet();
            foreach (DataRow dr in dtProvider.Rows)
            {
                providerDs.Tables["Provider"].ImportRow(dr);
            }

            LocalPlanScheduleReport rpt = new LocalPlanScheduleReport();
            TravelAgentReport providersubrpt = new TravelAgentReport();
            GuideReport guidesubrpt = new GuideReport();

            rpt.DataSource = scheduleDs;
            providersubrpt.DataSource = providerDs;
            guidesubrpt.DataSource = guideDs;
            rpt.GuideSubreport.ReportSource = guidesubrpt;
            rpt.ProviderSubreport.ReportSource = providersubrpt;

            if (btn.Equals(btnPreview))
                rpt.ShowPreviewDialog();
            else
                rpt.PrintDialog();
        }

        private void btnRemark_Click(object sender, EventArgs e)
        {
            panelRemark.Visible = true;
        }

        private void btnRemarkClose_Click(object sender, EventArgs e)
        {
            TeamGroupCtrl.UpdateTourGroupLocalRemark(lblTourGroupID.Text, mbLocalRemark.Text);
            panelRemark.Visible = false;
        }

        private void btnGuest_Click(object sender, EventArgs e)
        {
            GuestListForm guestListForm = new GuestListForm(lblTourGroupID.Text);
            guestListForm.ShowDialog(this);
        }

        private void tbLocalTourgroupRowState_CheckedChanged(object sender, EventArgs e)
        {
            if (tbLocalTourgroupRowState.Checked)//团已处理
                TeamGroupCtrl.UpdateTourGroupLocalTourgroupRowState(lblTourGroupID.Text, 2);
            else//去掉则置为团计划已经拷贝过来
                TeamGroupCtrl.UpdateTourGroupLocalTourgroupRowState(lblTourGroupID.Text, 1);
        }

        #endregion

        #region 行程计划GridView事件处理

        private void StartAndEndCityEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            //暂时屏蔽，用LookUpEdit提供的城市的选择方式

            DevExpress.XtraEditors.ButtonEdit btnEdit = sender as DevExpress.XtraEditors.ButtonEdit;
            CitySelectedToolForm city = new CitySelectedToolForm();

            if (city.ShowDialog(this) == DialogResult.OK)
                btnEdit.EditValue = city.ReturnCityName;

        }

        private void TrafficEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            string TrafficType = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, scheduleGridView.Columns["TrafficType"]).ToString();
            //string localPlanScheduleId = scheduleGridView.GetDataRow(scheduleGridView.FocusedRowHandle)["LocalPlanScheduleID"].ToString();

            if (string.IsNullOrEmpty(TrafficType))
            {

                MessageBox.Show("您还没有选择交通工具类型！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            DevExpress.XtraEditors.ButtonEdit btnEdit = sender as DevExpress.XtraEditors.ButtonEdit;
            switch (EnumHelper.Traffic_Str2Enum(TrafficType, true))//CommonEnum.GetTrafficType(TrafficType))
            {
                case TrafficTypeEnum.飞机:
                    FlightOrderForm flightOrderForm = new FlightOrderForm()
                    {
                        _StartCity = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, scheduleGridView.Columns["StartCity"]).ToString(),
                        _EndCity = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, scheduleGridView.Columns["DestinationCity"]).ToString(),
                    };
                    if (flightOrderForm.ShowDialog(this) == DialogResult.OK)//设置各项返回值到表格中
                    {
                        btnEdit.EditValue = flightOrderForm._FlightCode;
                        //scheduleGridView.SetRowCellValue(scheduleGridView.FocusedRowHandle, "StartCity", flightOrderForm._StartCity);
                        //scheduleGridView.SetRowCellValue(scheduleGridView.FocusedRowHandle, "DestinationCity", flightOrderForm._EndCity);
                        string journeyType = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, "Journeytype").ToString();
                        switch (EnumHelper.Journey_Str2Enum(journeyType, true))
                        {
                            case JourneyTypeEnum.入境:
                            case JourneyTypeEnum.抵:
                                scheduleGridView.SetRowCellValue(scheduleGridView.FocusedRowHandle, "Time", flightOrderForm._EndTime);
                                break;
                            case JourneyTypeEnum.离境:
                            case JourneyTypeEnum.离:
                                scheduleGridView.SetRowCellValue(scheduleGridView.FocusedRowHandle, "Time", flightOrderForm._StartTime);
                                break;
                            default:
                                break;
                        }
                    }
                    break;
                case TrafficTypeEnum.火车:
                    TrainOrderForm trainOrderForm = new TrainOrderForm()
                    {
                        _StartCity = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, scheduleGridView.Columns["StartCity"]).ToString(),
                        _EndCity = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, scheduleGridView.Columns["DestinationCity"]).ToString(),
                    };
                    if (trainOrderForm.ShowDialog(this) == DialogResult.OK)//设置各项返回值到表格中
                    {
                        btnEdit.EditValue = trainOrderForm._TrainCode;
                        //scheduleGridView.SetRowCellValue(scheduleGridView.FocusedRowHandle, "StartCity", trainOrderForm._StartCity);
                        //scheduleGridView.SetRowCellValue(scheduleGridView.FocusedRowHandle, "DestinationCity", trainOrderForm._EndCity);
                        string journeyType = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, "Journeytype").ToString();
                        switch (EnumHelper.Journey_Str2Enum(journeyType, true))
                        {
                            case JourneyTypeEnum.入境:
                            case JourneyTypeEnum.抵:
                                scheduleGridView.SetRowCellValue(scheduleGridView.FocusedRowHandle, "Time", trainOrderForm._EndTime);
                                break;
                            case JourneyTypeEnum.离境:
                            case JourneyTypeEnum.离:
                                scheduleGridView.SetRowCellValue(scheduleGridView.FocusedRowHandle, "Time", trainOrderForm._StartTime);
                                break;
                            default:
                                break;
                        }
                    }
                    break;
                case TrafficTypeEnum.汽车:
                    MessageBox.Show("预留调用实时的‘汽车’服务信息！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
                default:
                    MessageBox.Show("您选择的交通工具类型目前不被支持！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
            }

        }

        private void TravelAgencyNameEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            string localPlanScheduleId = scheduleGridView.GetDataRow(scheduleGridView.FocusedRowHandle)["LocalPlanScheduleID"].ToString();
            TravelSelectedToolForm travelForm = new TravelSelectedToolForm()
            {
                _TourGroupID = lblTourGroupID.Text,
                _TourGroupState = lblTourGroupName.Text,
                _TourGroupScheduleID = int.Parse(localPlanScheduleId)
            };
            if (travelForm.ShowDialog(this) == DialogResult.OK)
            {
                DevExpress.XtraEditors.ButtonEdit btnEdit = sender as DevExpress.XtraEditors.ButtonEdit;
                btnEdit.EditValue = travelForm.ReturnTravelAgencyName;
                scheduleGridView.SetRowCellValue(scheduleGridView.FocusedRowHandle, "TravelAgencyID", travelForm.ReturnTravelAgencyID);
                scheduleGridView.SetRowCellValue(scheduleGridView.FocusedRowHandle, "Reception", travelForm.ReturnContact);
            }
        }

        #endregion

        private void LocalPlanScheduleForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            //激发行程计划的GrideView数据更新
            if (scheduleGridView.FocusedRowModified)
                scheduleGridView.FocusedRowHandle = scheduleGridView.FocusedRowHandle == 0 ? 1 : 0;
            if (providerListGridView.FocusedRowModified)
                providerListGridView.FocusedRowHandle = providerListGridView.FocusedRowHandle == 0 ? 1 : 0;
        }

        private void scheduleGridView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            LoadProvidersListData();
        }
        private void cbCalendarDisplay_CheckedChanged(object sender, EventArgs e)
        {
            //刷新
            LoadProvidersListData();
        }

        #region 供应商清单及签单打印处理
        private DataTable _dtProviderListData;
        /// <summary>
        /// 根据是否为日程显示娱乐的预订信息
        /// </summary>
        private void LoadProvidersListData()
        {
            if (cbCalendarDisplay.Checked == false)
            {
                _dtProviderListData = LocalTeamGroupCtrl.GetEntertainmentRestaurantAndVehicleForProvider(lblTourGroupID.Text, _currentPageNumber, false);
                providerListGridControl.DataSource = AddGridSelectedColumn(_dtProviderListData);
            }
            else if (scheduleGridView.FocusedRowHandle >= 0)
            {
                string localPlanScheduleId = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, "LocalPlanScheduleID").ToString();
                _dtProviderListData =LocalTeamGroupCtrl.GetEntertainmentRestaurantAndVehicleForProvider(localPlanScheduleId,_currentPageNumber, true);
                providerListGridControl.DataSource = AddGridSelectedColumn(_dtProviderListData);
            }
            _dtProviderListData.ColumnChanged += new DataColumnChangeEventHandler(ProviderListData_ColumnChanged);

        }

        #region 修改预订信息后的自动保存

        void ProviderListData_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {
            EntertainmenRestaurantOrderEntity entertainmentOrder = new EntertainmenRestaurantOrderEntity();
            
            entertainmentOrder.EntertainmentOrderID = int.Parse(e.Row["EntertainmentOrderID"].ToString());/*重点字段*/
            entertainmentOrder.ServiceName = e.Row["ServiceName"].ToString();
            entertainmentOrder.Remark = e.Row["Remark"].ToString();

            EntertainmenRestaurantOrderCtrl.UpdateEntertainmenRestaurantOrderPart( entertainmentOrder);

        }
        #endregion
  
        /// <summary>
        /// 打印或预览签单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrintAndPreviewStatements_Click(object sender, EventArgs e)
        {
            DialogResult dResult = sender.Equals(btnPreviewStatements) ? DialogResult.Retry : MessageBox.Show("确认打印签单吗？", "打印提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (DialogResult.Yes == dResult || DialogResult.Retry == dResult)
            {
                providerListGridView.ClearSelection();
                int[] rowIds = MutilRow(providerListGridView);

                if (rowIds.Length == 0) return;

                SignBillDataSet ds = new SignBillDataSet();

                string expenseId;
                for (int i = 0; i < rowIds.Length; i++)
                {
                    if (sender.Equals(btnPrintStatements))
                    {
                        //变更导游报销方式
                        expenseId = providerListGridView.GetDataRow(rowIds[i])["ExpenseID"].ToString();
                        ExpensesCtrl.UpdateExpenseDataWipeOffMethod(expenseId, WipeOffMethodEnum.签单报账);
                    }
                    ds.Tables["EntertainmenRestaurantOrder"].ImportRow(providerListGridView.GetDataRow(rowIds[i]));
                }
                SignBillReport rpt = new SignBillReport();
                rpt.DataSource = ds;
                if (sender.Equals(btnPrintStatements))
                    rpt.PrintDialog();
                else
                    new PrintPreviewForm(rpt, "").ShowDialog();
            }
        }
        /// <summary>
        /// 打印备份签单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>        
        private void btnPrintBackupSignbill_Click(object sender, EventArgs e)
        {

            //获得导游信息
            //DataTable dtGuide = GuideArrangeCtrl.GetGuideInfoForPrint(lblTourGroupID.Text);

            //创建娱乐预定信息内容
            EntertainmenRestaurantOrderEntity entertainmentOrder = new EntertainmenRestaurantOrderEntity();
            entertainmentOrder.OrderState = OrderStateEnum.未订.ToString();/*重点内容，初始化订单状态为‘未定’*/
            entertainmentOrder.TourgroupID = lblTourGroupID.Text;
            entertainmentOrder.TourgroupName = lblTourGroupName.Text;

            entertainmentOrder.ProviderID = -1;
            entertainmentOrder.ProviderName = "";
            entertainmentOrder.ServiceName = "";
            entertainmentOrder.ContractPath = "";

            entertainmentOrder.LocalPlanScheduleID = int.Parse(scheduleGridView.GetRowCellValue(0, "LocalPlanScheduleID").ToString());
            entertainmentOrder.ServiceDate = DateTime.Parse(scheduleGridView.GetRowCellValue(0, "Date").ToString()).ToString("yyyy-MM-dd");
            entertainmentOrder.AdultUnitPrice = 0;
            entertainmentOrder.AccompanyUnitPrice = 0;
            entertainmentOrder.AccompanyNum = 0;
            entertainmentOrder.AdultNum = 0;
            entertainmentOrder.ChildNum = 0;
            entertainmentOrder.ChildUnitPrice = 0;
            entertainmentOrder.OthersCost = 0;
            entertainmentOrder.CiceroniName = tbCiceroni.Text;//dtGuide.Rows.Count > 0 ? dtGuide.Rows[0]["CiceroniName"].ToString() : "待告";
            entertainmentOrder.CiceroniPhone = tbPhone.Text;//tGuide.Rows.Count > 0 ? dtGuide.Rows[0]["Phone"].ToString() : "待告";
            entertainmentOrder.Remark = "";

            //创建费用
            ExpenseEntity expense = new ExpenseEntity()
            {
                //ExpenseID = _ExpenseID,
                TourgroupID = lblTourGroupID.Text,
                TourgroupName = lblTourGroupName.Text,
                TourGroupScheduleID = int.Parse(scheduleGridView.GetRowCellValue(0, "TourGroupScheduleID").ToString()),
                ProviderID = -1,
                ProviderName = "",
                ServiceName = "",
                Budget = 0,
                PayTotal = 0,
                ApplyPayTotal = 0,
                AdjustAmount = 0,
                Status = ExpenseStatusEnum.计划.ToString(),
                TypeBelong = ProviderTypeEnum.景点.ToString(),
                ApplyPay = 0,
                PayStatus = PayApplyStatusEnum.未付.ToString(),
                CreateByUserName = Thread.CurrentPrincipal.Identity.Name, //UserInfoCtrl.GetNameByUserName(Thread.CurrentPrincipal.Identity.Name)
                CreateTime = DateTime.Now.ToString("yyyy-MM-dd"),
                ExpenseTypeID = 5,//所属费用类型(费用类型表中存储着编号，此编号是固定的，1房费、2团费、3餐费、4交通费、5门票、6杂费)
                ExpenseType = BaseInfoCtrl.GetExpenseTypeNameByID(5),//同上
                WipeOffMethod = WipeOffMethodEnum.签单报账.ToString()
            };
            EntertainmenRestaurantOrderCtrl.CreateEntertainmenRestaurantOrderAndExpenseData(expense, entertainmentOrder);
            LoadProvidersListData();


            //SignBillDataSet ds = new SignBillDataSet();
            //SignBillDataSet.EntertainmenRestaurantOrderRow newOrderRow = ds.EntertainmenRestaurantOrder.NewEntertainmenRestaurantOrderRow();

            //newOrderRow.EntertainmentOrderID = EntertainmenOrderId;
            //ds.EntertainmenRestaurantOrder.Rows.Add(newOrderRow);

            //SignBillReport rpt = new SignBillReport();
            //rpt.DataSource = ds;
            //rpt.PrintDialog();
 
        }
        private void tbSelectedAll_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataRow dr in _dtProviderListData.Rows)
                dr["Selected"] = tbSelectedAll.Checked;
        }

        #endregion

        #region 标签页显示
        private void tourGroupScheduleTabControl_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            switch (e.Page.Name)
            {
                case "Page1"://日程
                    LoadProvidersListData();
                    break;
                case "Page2"://备注
                    memoEditRemark.Text = TeamGroupCtrl.GetTourGroupScheduleRemark(lblTourGroupID.Text);
                    break;
                case "Page3"://大计划
                    DataSet ds = TeamGroupCtrl.GetTourGroupSchedule(lblTourGroupID.Text);
                    if(ds.Tables.Count>0)
                    tourGroupScheduleGridControl.DataSource = ds.Tables[0]; 
                    break;
                default:
                    break;
            }
        }
        #endregion

        #region 打钩选择处理

        /// <summary>
        /// 添加‘选择’附加列
        /// </summary>
        /// <param name="dtSource"></param>
        /// <returns></returns>
        private DataTable AddGridSelectedColumn(DataTable dtSource)
        {
            dtSource.Columns.Add("Selected", typeof(bool));
            return dtSource;
        }

        private void SelectedCheckEdit_CheckedChanged(object sender, EventArgs e)
        {
            #region 打钩选择行

            int iFocuse = providerListGridView.FocusedRowHandle;
            providerListGridView.ClearSelection();

            if ((sender as CheckEdit).Checked)
                providerListGridView.SelectRow(iFocuse);

            int[] rowIds = MutilRow(providerListGridView);

            #endregion
        }
        private int[] MutilRow(GridView gv)
        {
            object selected;
            for (int i = 0; i < gv.RowCount; i++)
            {
                selected = gv.GetRowCellValue(i, "Selected");

                if (string.IsNullOrEmpty(selected.ToString())) continue;

                if (Convert.ToBoolean(selected) == true)
                {
                    gv.SelectRow(i);
                }
            }
            return gv.GetSelectedRows();
        }

        #endregion

        private void tbCiceroni_Properties_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

        }


    }
}
